<template>
    <div class="register-container">
      <el-card class="register-card">
        <h2>注册</h2>
        <el-form ref="registerForm" :model="registerData" label-width="100px" :rules="rules">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="registerData.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="registerData.password"
              type="password"
              placeholder="请输入密码"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitRegister">注册</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </template>
  
  <script setup>
  import { ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import { register } from '@/services/api';
  import router from '@/router';
  const registerData = ref({
    username: '',
    password: ''
  });
  
  const rules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 20, message: '用户名长度应在3到20个字符之间', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度应在6到20个字符之间', trigger: 'blur' }
    ]
  };
  
  const registerForm = ref(null);
  
  const submitRegister = async () => {
    try {
      await registerForm.value.validate(); // 表单校验
      const response = await register({
        username: registerData.value.username,
        password: registerData.value.password
      });
      ElMessage.success(response.data.message || '注册成功');
      // 注册成功后可以跳转到登录页面或其他页面
      router.push({ name: 'Login' });
    } catch (err) {
      if (err.response) {
        ElMessage.error(err.response.data.message || '注册失败');
      } else {
        ElMessage.error('注册失败，请稍后再试');
      }
    }
  };
  
  const resetForm = () => {
    registerForm.value.resetFields();
  };
  </script>
  
  <style scoped>
  .register-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f0f2f5;
  }
  
  .register-card {
    width: 400px;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  </style>